package jEDF.Hypnogram;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;

import jEDF.EDF.*;
import jEDF.Exceptions.*;
import jEDF.JEDF.*;

/**
 *
 * <p>Titre : jEDF</p>
 * <p>Description : Java European Data Format Viewer and Analyser</p>
 * <p>Author : Nizar Kerkeni</p>
 * <p>Copyright : Copyright (c) 2003-2006</p>
 * <p>Version 2.0</p>
 */
public class NewHypnogramDialogAS extends javax.swing.JDialog {

    private JTabbedPane jtpCreationChoice = new JTabbedPane();
    private JButton jbOKLoad = new JButton(JEDFMainWindow.getLocalizedString(
            "Load"));
    private JButton jbBrowseLoad = new JButton(JEDFMainWindow.getLocalizedString("Browse"));
    private JTextField jtfFileName = new JTextField();
    private JLabel jlFileChoose = new JLabel(JEDFMainWindow.getLocalizedString(
            "Please choose an input file :"));
    private JPanel jpExtract = new JPanel(new BorderLayout());
    private JComboBox jcbSignals = new JComboBox();
    private JButton jbOkExtract = new JButton(JEDFMainWindow.getLocalizedString(
            "Extract"));
    private JLabel jlExtractFromSignal = new JLabel(JEDFMainWindow.getLocalizedString(
            "Please choose the signal to extract the hypnogram from :"));
    private JButton jbOKNew = new JButton(JEDFMainWindow.getLocalizedString(
            "Create"));
    private JComboBox jcbEpochDuration = new JComboBox();
    private JLabel jlDurationRequest = new JLabel(JEDFMainWindow.getLocalizedString(
            "Please choose the desired epoch duration (in s):"));
    private JTextField jtfNewFile = new JTextField();
    private JLabel jlNewFile = new JLabel(JEDFMainWindow.getLocalizedString(
            "Please choose the file to record the hypnogram to:"));
    private JButton jbBrowseNew = new JButton(JEDFMainWindow.getLocalizedString(
            "Browse"));
    private JPanel jpLoadFromFile = new JPanel(new BorderLayout());
    private JPanel jpNewHypnogram = new JPanel(new BorderLayout());
    private JButton jbCancelExtract = new JButton(JEDFMainWindow.getLocalizedString("Cancel"));
    private JButton jbCancelLoad = new JButton(JEDFMainWindow.getLocalizedString("Cancel"));
    private JButton jbCancelNew = new JButton(JEDFMainWindow.getLocalizedString(
            "Cancel"));
    //Amplitude frontal como parametro para N3
    private JCheckBox jchAmplF = new JCheckBox();
    private boolean m_bAmplF = true;
    private JTextField jtfAmplF = new JTextField();
    private JTextField jtfPercF = new JTextField();
    private int m_AmplF = 21;
    private double m_PercF = 0.8;
    //Amplitude de movimento como parâmetro para N3
    private JCheckBox jchAmplM = new JCheckBox();
    private boolean m_bAmplM = true;
    private JTextField jtfAmplM = new JTextField();
    private JTextField jtfPercM = new JTextField();
    private int m_AmplM = 95;
    private double m_PercM = 0.2;
    //Filtro Antialiasing
    private JCheckBox jchAA = new JCheckBox();
    private boolean m_bAA = true;

    public int getAmplF() {
        return m_AmplF;
    }

    public void setAmplF(int m_AmplF) {
        this.m_AmplF = m_AmplF;
    }

    public int getAmplM() {
        return m_AmplM;
    }

    public void setAmplM(int m_AmplM) {
        this.m_AmplM = m_AmplM;
    }

    public double getPercF() {
        return m_PercF;
    }

    public void setPercF(double m_PercF) {
        this.m_PercF = m_PercF;
    }

    public double getPercM() {
        return m_PercM;
    }

    public void setPercM(double m_PercM) {
        this.m_PercM = m_PercM;
    }

    public boolean isAmplF() {
        return m_bAmplF;
    }

    public void setAmplF(boolean m_bAmplF) {
        this.m_bAmplF = m_bAmplF;
    }

    public boolean isAmplM() {
        return m_bAmplM;
    }

    public void setAmplM(boolean m_bAmplM) {
        this.m_bAmplM = m_bAmplM;
    }

    public boolean getAA() {
        return m_bAA;
    }

    public void setAA(boolean m_bAA) {
        this.m_bAA = m_bAA;
    }
    private JEDFHypnogram hypnogram = null;
    private EDFFile edfFile = null;

    /**
     * @param mainWindow the main window
     * @param polysomnograph the corresponding polysomnograph
     * @param hypnogram the hypnogram we want to set up
     * @param isLoading if true, display the load panel otherwise display the new panel
     */
    public NewHypnogramDialogAS(JEDFMainWindow mainWindow,
            Polysomnograph polysomnograph,
            JEDFHypnogram hypnogram, boolean isLoading) {
        super(mainWindow, true);

        this.hypnogram = hypnogram;
        this.edfFile = mainWindow.getEDFFile();

        arrange();
        addListeners();

        jcbEpochDuration.addItem("1s");
        jcbEpochDuration.addItem("2s");
        jcbEpochDuration.addItem("4s");
        jcbEpochDuration.addItem("5s");

        jcbEpochDuration.addItem("10s");
        jcbEpochDuration.addItem("20s");
        jcbEpochDuration.addItem("30s");
        jcbEpochDuration.addItem("1min");
        jcbEpochDuration.addItem("2min");
        jcbEpochDuration.addItem("3min");
        jcbEpochDuration.addItem("4min");
        jcbEpochDuration.setSelectedItem(polysomnograph.getEpochDuration()
                + "s");

        String newFileName = EDFFileFilter.changeFileExtension(edfFile.getFile(), ".hyp");

        if (isLoading) {
            jtpCreationChoice.setSelectedComponent(jpLoadFromFile);
        } else {
            jtpCreationChoice.setSelectedComponent(jpNewHypnogram);
        }

        String[] signalsLabels = edfFile.getSignalsLabel();

        if (signalsLabels == null) {
            return;
        }
        if (signalsLabels.length <= 0) {
            return;
        }

        for (int i = 0; i < signalsLabels.length; i++) {
            jcbSignals.addItem(signalsLabels[i]);
        }

        jpLoadFromFile.setPreferredSize(new Dimension(450, 0));
        jtfNewFile.setText(newFileName);
        jtfFileName.setText(newFileName);
        setTitle(JEDFMainWindow.getLocalizedString("Hypnogram creation"));
        setSize(new Dimension(900, 175));
        //setMinimumSize(new Dimension(/*450*/900,175));
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    //IASx01 by FO - INICIO - Inclusão do Auto Scoring
    /**
     * @param mainWindow the main window
     * @param polysomnograph the corresponding polysomnograph
     * @param hypnogram the hypnogram we want to set up
     * @param isLoading if true, display the load panel otherwise display the new panel
     * @param isAutoScoring if true, disables epoch duration selection and sets to 30s
     */
    public NewHypnogramDialogAS(JEDFMainWindow mainWindow,
            Polysomnograph polysomnograph,
            JEDFHypnogram hypnogram, boolean isLoading, boolean isAutoScoring) {
        super(mainWindow, true);

        this.hypnogram = hypnogram;
        this.edfFile = mainWindow.getEDFFile();

        arrange();
        addListeners();

        jcbEpochDuration.addItem("1s");
        jcbEpochDuration.addItem("2s");
        jcbEpochDuration.addItem("4s");
        jcbEpochDuration.addItem("5s");

        jcbEpochDuration.addItem("10s");
        jcbEpochDuration.addItem("20s");
        jcbEpochDuration.addItem("30s");
        jcbEpochDuration.addItem("1min");
        jcbEpochDuration.addItem("2min");
        jcbEpochDuration.addItem("3min");
        jcbEpochDuration.addItem("4min");
        jcbEpochDuration.setSelectedItem(polysomnograph.getEpochDuration()
                + "s");

        if (isAutoScoring) {
            jcbEpochDuration.setEnabled(false);
        }


        String newFileName = EDFFileFilter.changeFileExtension(edfFile.getFile(), ".hyp");

        if (isLoading) {
            jtpCreationChoice.setSelectedComponent(jpLoadFromFile);
        } else {
            jtpCreationChoice.setSelectedComponent(jpNewHypnogram);
        }

        String[] signalsLabels = edfFile.getSignalsLabel();

        if (signalsLabels == null) {
            return;
        }
        if (signalsLabels.length <= 0) {
            return;
        }

        for (int i = 0; i < signalsLabels.length; i++) {
            jcbSignals.addItem(signalsLabels[i]);
        }

        jpLoadFromFile.setPreferredSize(new Dimension(450, 0));
        jtfNewFile.setText(newFileName);
        jtfFileName.setText(newFileName);
        setTitle(JEDFMainWindow.getLocalizedString("Hypnogram creation"));
        setSize(new Dimension(900, 175));
        //setMinimumSize(new Dimension(/*450*/900,175));
        pack();
        setLocationRelativeTo(null);
//        setVisible(true);
    }
    //IASx01 by FO - FIM - Inclusão do Auto Scoring

    private void arrange() {
        getContentPane().add(jtpCreationChoice);
        //jtpCreationChoice.addTab(JEDFMainWindow.getLocalizedString("Extract from signal"), jpExtract);
        //jtpCreationChoice.addTab(JEDFMainWindow.getLocalizedString("Load from file"), jpLoadFromFile);
        jtpCreationChoice.addTab(JEDFMainWindow.getLocalizedString("New Hypnogram"), jpNewHypnogram);

        jpExtract.add(jlExtractFromSignal, BorderLayout.NORTH);
        JPanel jpExtractCenter = new JPanel();
        jpExtractCenter.add(jcbSignals);
        jpExtract.add(jpExtractCenter, BorderLayout.CENTER);
        JPanel jpExtractSouth = new JPanel();
        jpExtractSouth.add(jbOkExtract);
        jpExtractSouth.add(jbCancelExtract);
        jpExtract.add(jpExtractSouth, BorderLayout.SOUTH);

        jpLoadFromFile.add(jlFileChoose, BorderLayout.NORTH);
        JPanel jpLoadCenter = new JPanel();
        jpLoadCenter.add(jtfFileName);
        jpLoadCenter.add(jbBrowseLoad);
        jpLoadFromFile.add(jpLoadCenter, BorderLayout.CENTER);
        JPanel jpLoadSouth = new JPanel();
        jpLoadSouth.add(jbOKLoad);
        jpLoadSouth.add(jbCancelLoad);
        jpLoadFromFile.add(jpLoadSouth, BorderLayout.SOUTH);

        JPanel jpNewNorth = new JPanel(new BorderLayout());
        JPanel jpNewFile = new JPanel();
        jpNewFile.add(jtfNewFile);
        jpNewFile.add(jbBrowseNew);
        JPanel jpNewDuration = new JPanel();

        jpNewDuration.add(jlDurationRequest);
        jpNewDuration.add(jcbEpochDuration);

        jpNewNorth.add(jlNewFile, BorderLayout.NORTH);
        jpNewNorth.add(jpNewFile, BorderLayout.CENTER);

        //Adiciona parametros para N3 de canal frontal
        JPanel jpFrontal = new JPanel();
        jpFrontal.add(new JLabel("N3 -"));
        jpFrontal.add(jchAmplF);
        jpFrontal.add(new JLabel("Amplitude frontal maior que"));
        jpFrontal.add(jtfAmplF);
        jtfAmplF.setColumns(2);
        jtfAmplF.setText(String.valueOf(m_AmplF));
        jpFrontal.add(new JLabel("em pelo menos"));
        jpFrontal.add(jtfPercF);
        jpFrontal.add(new JLabel("% da época"));
        jtfPercF.setColumns(2);
        jtfPercF.setText(String.valueOf(m_PercF));
        jchAmplF.setSelected(m_bAmplF);

        //Adiciona parametros para N3 de canal de movimento
        JPanel jpMovimento = new JPanel();
        jpMovimento.add(new JLabel("N3 -"));
        jpMovimento.add(jchAmplM);
        jpMovimento.add(new JLabel("Amplitude de perna maior que"));
        jpMovimento.add(jtfAmplM);
        jtfAmplM.setColumns(2);
        jtfAmplM.setText(String.valueOf(m_AmplM));
        jpMovimento.add(new JLabel("em no máximo"));
        jpMovimento.add(jtfPercM);
        jpMovimento.add(new JLabel("% da época"));
        jtfPercM.setColumns(2);
        jtfPercM.setText(String.valueOf(m_PercM));
        jchAmplM.setSelected(m_bAmplM);

        //Adiciona opção de filtro AntiAliasing
        JPanel jpAntiAliasing = new JPanel();
        jpAntiAliasing.add(new JLabel("AntiAliasing Filtering"));
        jpAntiAliasing.add(jchAA);



        jpNewHypnogram.setLayout(new BoxLayout(jpNewHypnogram, BoxLayout.Y_AXIS));

        jpNewHypnogram.add(jpNewNorth);
        //jpNewHypnogram.add(jpNewDuration);
        //jpNewHypnogram.add(jpFrontal);
        //jpNewHypnogram.add(jpMovimento);
        jpNewHypnogram.add(jpAntiAliasing);

        JPanel jpNewSouth = new JPanel();
        jpNewSouth.add(jbOKNew);
        jpNewSouth.add(jbCancelNew);

        jpNewHypnogram.add(jpNewSouth);

        jtfFileName.setColumns(35);
        jtfNewFile.setColumns(35);
    }

    private void addListeners() {
        jbCancelExtract.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                cancelSelected();
            }
        });
        jbCancelNew.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                cancelSelected();
            }
        });
        jbCancelLoad.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                cancelSelected();
            }
        });

        jbBrowseLoad.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                browseLoad();
            }
        });

        jbBrowseNew.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                browseNew();
            }
        });

        jbOkExtract.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                okExtract();
            }
        });

        jbOKNew.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                okNew();
            }
        });

        jbOKLoad.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                okLoad();
            }
        });
    }

    private void cancelSelected() {
        dispose();
    }

    private void okExtract() {
        try {
            hypnogram.loadSignalData(edfFile.getSignal(jcbSignals.getSelectedIndex()));
            dispose();
        } catch (NotAHypnogramException e) {
            JOptionPane.showMessageDialog(this,
                    JEDFMainWindow.getLocalizedString(
                    "The specified signal does not appear to contain hypnogram data."),
                    JEDFMainWindow.getLocalizedString(
                    "Error"),
                    JOptionPane.ERROR_MESSAGE);
        } catch (UserCancelException e) {
        }
    }

    private void okLoad() {
        EDFFile edfFile = null;
        try {
            edfFile = new EDFFile(new File(jtfFileName.getText()));

            String filename = jtfNewFile.getText();
            filename = filename.replaceAll(".hyp", "_gabarito.hyp");
            hypnogram.setFilenameGabarito(filename);

            if (!edfFile.isItAHypnogramRecord()) {
                throw new NotAHypnogramException();
            }
            hypnogram.loadEDFFile(edfFile);

            dispose();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this,
                    JEDFMainWindow.getLocalizedString(
                    "The specified file does not appear to contain hypnogram data."),
                    JEDFMainWindow.getLocalizedString(
                    "Error"),
                    JOptionPane.ERROR_MESSAGE);
        } catch (NotAHypnogramException e) {
            JOptionPane.showMessageDialog(this,
                    JEDFMainWindow.getLocalizedString(
                    "The specified file does not appear to contain hypnogram data."),
                    JEDFMainWindow.getLocalizedString(
                    "Error"),
                    JOptionPane.ERROR_MESSAGE);
        } catch (UserCancelException e) {
        }
    }

    private void okNew() {


        m_PercF = Double.parseDouble(jtfPercF.getText());
        m_AmplF = Integer.parseInt(jtfAmplF.getText());
        m_bAmplF = jchAmplF.isSelected();

        m_PercM = Double.parseDouble(jtfPercM.getText());
        m_AmplM = Integer.parseInt(jtfAmplM.getText());
        m_bAmplM = jchAmplM.isSelected();
        m_bAA = jchAA.isSelected();


        try {
            int[] durations = {1, 2, 4, 5, 10, 20, 30, 60, 120, 180, 240};
            int duration = durations[jcbEpochDuration.getSelectedIndex()];

            File file = new File(jtfNewFile.getText());

            String filename = jtfNewFile.getText();
            filename = filename.replaceAll(".hyp", "_gabarito.hyp");
            hypnogram.setFilenameGabarito(filename);

            if (!file.exists()) {
                file.createNewFile();
            } else if (file.isFile()) {
                int result = JOptionPane.showConfirmDialog(this,
                        JEDFMainWindow.getLocalizedString(
                        "Continuing will replace the content of the specified file.\nAre you sure you want to continue ?"),
                        JEDFMainWindow.getLocalizedString("Warning"),
                        JOptionPane.YES_NO_OPTION);
                if (result != JOptionPane.YES_OPTION) {
                    return;
                }
                file.delete();
            } else {
                throw new IOException();
            }

            hypnogram.createHypnogram(file, duration);
            dispose();
        } catch (NumberFormatException nfe) {
            JOptionPane.showMessageDialog(this,
                    JEDFMainWindow.getLocalizedString(
                    "Please input an integer between 1 and 60 inclusive."),
                    JEDFMainWindow.getLocalizedString(
                    "Error"),
                    JOptionPane.ERROR_MESSAGE);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this,
                    JEDFMainWindow.getLocalizedString("Cannot create the file : please specify a correct filename\nand verify that you have the rights to write to it."),
                    JEDFMainWindow.getLocalizedString(
                    "Error"),
                    JOptionPane.ERROR_MESSAGE);
        }

    }

    private void browseLoad() {
        JFileChooser chooser = new JFileChooser(edfFile.getFile());

        String[] extensions = {"hyp"};

        EDFFileFilter edfFileFilter = new EDFFileFilter(extensions,
                JEDFMainWindow.getLocalizedString("Hypnogram record"));

        chooser.setFileFilter(edfFileFilter);

        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            String chosenFile = chooser.getSelectedFile().getAbsolutePath();

            jtfFileName.setText(chosenFile);
        }
    }

    private void browseNew() {
        JFileChooser chooser = new JFileChooser(edfFile.getFile());

        String[] extensions = {"hyp"};

        EDFFileFilter edfFileFilter = new EDFFileFilter(extensions,
                JEDFMainWindow.getLocalizedString("Hypnogram record"));

        chooser.setFileFilter(edfFileFilter);

        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            String chosenFile = chooser.getSelectedFile().getAbsolutePath();

            if (!chosenFile.endsWith(".hyp")) {
                chosenFile += ".hyp";
            }
            jtfNewFile.setText(chosenFile);
        }
    }
}
